package cn.itrip.auth.controller;

import cn.itrip.common.MD5;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import springfox.documentation.annotations.ApiIgnore;
import cn.itrip.auth.service.ItripUserService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.userinfo.ItripUserVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.ErrorCode;

/**
 * 用户管理控制器
 * @author hduser
 */
@Controller
@RequestMapping(value = "/api")
public class UserController {
    @Resource
    private ItripUserService itripUserService;

    @ApiIgnore
    @RequestMapping("/register")
    public String showRegisterForm() {
        return "register";
    }

    /**
     * 使用邮箱注册
     * @param userVO
     * @return
     */
    @ApiOperation(value = "使用邮箱注册",httpMethod = "POST",protocols = "HTTP",produces = "application/json",
        response = Dto.class,notes = "使用邮箱注册")
    @RequestMapping(value="/doregister",method=RequestMethod.POST,produces="application/json")
    public @ResponseBody Dto doRegister(
            @ApiParam(name = "userVO",value = "用户实体",required = true)
            @RequestBody ItripUserVO userVO) {
        if (!this.validEmail(userVO.getUserCode()))
            return DtoUtil.returnFail("请使用正确的邮箱地址",ErrorCode.AUTH_ILLEGAL_USERCODE);
        ItripUser itripUser=new ItripUser();
        itripUser.setUserCode(userVO.getUserCode());
        itripUser.setUserPassword(userVO.getUserPassword());
        itripUser.setUserName(userVO.getUserName());
        try{
        if (null!=itripUserService.getItripUserCountByMap(userVO.getUserCode())){
            return DtoUtil.returnFail("用户已存在",ErrorCode.AUTH_USER_ALREADY_EXISTS);
        }else {
            itripUser.setUserPassword(MD5.getMd5(userVO.getUserPassword(),32));
            itripUserService.insertItripUser(itripUser);
            return DtoUtil.returnSuccess();
        }

        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(),ErrorCode.AUTH_UNKNOWN);
        }
    }

    /**
     * 使用手机注册
     * @param userVO
     * @return
     */
    @ApiOperation(value = "使用手机注册",httpMethod = "POST",protocols = "HTTP",produces = "application/json",
            response = Dto.class,notes = "使用手机注册")
    @RequestMapping(value="/registerbyphone",method=RequestMethod.POST,produces = "application/json")
    public @ResponseBody Dto registerByPhone(
            @ApiParam(name = "userVO",value = "用户实体",required = true)
            @RequestBody ItripUserVO userVO){
        if (this.validPhone(userVO.getUserCode()))
            return DtoUtil.returnFail("请使用正确的手机号码", ErrorCode.AUTH_ILLEGAL_USERCODE);
            ItripUser itripUser=new ItripUser();
            itripUser.setUserCode(userVO.getUserCode());
            itripUser.setUserName(userVO.getUserName());
            try {
                if (null != itripUserService.getItripUserCountByMap(userVO.getUserCode())) {
                    return DtoUtil.returnFail("用户已存在", ErrorCode.AUTH_USER_ALREADY_EXISTS);
                } else {
                    itripUser.setUserPassword(MD5.getMd5(userVO.getUserPassword(), 32));
                    itripUserService.insertItripUserPhone(itripUser);
                    return DtoUtil.returnSuccess();
                }

            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_UNKNOWN);
            }


    }

    /**
     * 检查用户是否已注册
     * @param name
     * @return
     */
    @RequestMapping(value="/ckusr",method=RequestMethod.GET,produces= "application/json")
    public @ResponseBody Dto checkUser(
            @RequestParam String name) {

    return DtoUtil.returnSuccess();
    }

    @ApiOperation(value = "邮箱注册用户激活码验证",httpMethod = "PUT",
            protocols = "HTTP",produces = "application/json",
            response = Dto.class,notes = "邮箱注册用户激活码验证")
    @RequestMapping(value="/activate",method=RequestMethod.PUT,produces= "application/json")
    public @ResponseBody Dto activate(
            @ApiParam(name = "user",value = "邮箱账号",defaultValue = "fxy1231206@163.com")
            @RequestParam String user,
            @ApiParam(name = "code",value = "激活码",defaultValue = "")
            @RequestParam String code){
        try{
            if (itripUserService.activate(user,code)){
                return DtoUtil.returnSuccess("激活成功");
            }else {
                return DtoUtil.returnSuccess("激活失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("激活失败",ErrorCode.AUTH_UNKNOWN);
        }
    }

    @ApiOperation(value = "手机注册用户短信验证",httpMethod = "PUT",
            protocols = "HTTP",produces = "application/json",
            response = Dto.class,notes = "手机注册短信验证")
    @RequestMapping(value="/validatephone",method=RequestMethod.PUT,produces= "application/json")
    public @ResponseBody Dto validatePhone(
            @ApiParam(name = "user",value = "手机号码",defaultValue = "15574046225")
            @RequestParam String user,
            @ApiParam(name = "code",value = "验证码",defaultValue = "")
            @RequestParam String code){
        try{
            if (itripUserService.validatePhone(user,code)){
                return DtoUtil.returnSuccess("验证成功");
            }else {
                return DtoUtil.returnSuccess("验证失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("验证失败",ErrorCode.AUTH_UNKNOWN);
        }

    }

    /**			 *
     * 合法E-mail地址：
     * 1. 必须包含一个并且只有一个符号“@”
     * 2. 第一个字符不得是“@”或者“.”
     * 3. 不允许出现“@.”或者.@
     * 4. 结尾不得是字符“@”或者“.”
     * 5. 允许“@”前的字符中出现“＋”
     * 6. 不允许“＋”在最前面，或者“＋@”
     */
    private boolean validEmail(String email){
        String regex="^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        return Pattern.compile(regex).matcher(email).find();
    }
    /**
     * 验证是否合法的手机号
     * @param phone
     * @return
     */
    private boolean validPhone(String phone) {
        String regex="^1[3578]{1}\\d{8}$";
        return Pattern.compile(regex).matcher(phone).find();
    }
}
